/* 
    处理博文数据的逻辑
*/
const { sqlQuery } = require('../mysql/index')

const { StringDecoder } = require('string_decoder');
const { get } = require('http');
const decoder = new StringDecoder('utf8');

module.exports = {
    getBlogList, getBlogById, addBlog, visitBlog, searchBlog
}

//获取博文列表(分页)
async function getBlogList(page) {
    page = parseInt(page)
    let page_size = 8;//一页8条数据
    let sql =
        page == -1 ?
            `select id,title,time,sign,signId from blog_data;`
            :
            `select id,title,time,sign,signId from blog_data ORDER BY time desc limit ${(page - 1) * page_size},${page_size};`
    return new Promise(function (resolve, reject) {
        sqlQuery(sql, (data) => {
            //检测page值是否正确
            for (let i in data) {
                //console.log(data[i].sign);
                //将博文数据中的sign字段（String）转换成数组形式
                if (data[i].sign == null || data[i].sign == "") {
                }
                else {
                    data[i].sign = blogToArr(data[i].sign)
                    data[i].signId = blogToArr(data[i].signId).map(function (d) { return +d })
                }
                if (i == data.length - 1) {
                    if (page == -1) {
                        resolve(initArr(data, 0))
                    }
                    else {
                        resolve(data)
                    }

                }
            }
        })
    }
    )
}

//根据ID获取博文信息
async function getBlogById(uid) {
    let id = uid
    //获取博文信息
    let sql = `select * from blog_data where id=${id ? id : null};`
    //如果查询的id不存在或为空，则返回一个空值给前端
    return new Promise(function (resolve, reject) {
        sqlQuery(sql, (data) => {
            data[0].content = decoder.write(data[0].content)
            if (data[0].sign == null || data[0].sign == "") {
            }
            else {
                data[0].sign = blogToArr(data[0].sign)
                data[0].signId = blogToArr(data[0].signId).map(function (d) { return +d })
            }
            resolve(data)
        })
    })

}

//博文访问数++
async function visitBlog(uid) {
    let id = uid
    let sql = `update blog_data set visit=visit+1 where id=${id ? id : null};`
    return new Promise(function (resolve, reject) {
        sqlQuery(sql, data => {
            resolve('visit is already self-add')
        })
    })
}

//新增博文
async function addBlog(data) {
    let title = data.title;
    let time = data.time;
    let content = data.content;
    let sign = data.sign;//标签名字
    let color = data.signColor;//标签颜色

    /* 处理标签：
    1.遍历标签数组，判断其是否存在于标签表中：若存在，则获取该标签id存储进一个新的数组；
    若不存在，则在表中添加该标签，咱对其进行存储 ；
    2.标签数组和标签id数组都要转换成字符串的形式进行存储
    */

    //第一个方法，判断标签是否存在表中
    async function isChart() {
        let isRes = [];
        return new Promise(function (resolve, reject) {
            //没有标签时
            if (sign.length == 0) {
                resolve(isRes)
            }
            for (let i in sign) {
                let sql = `select count(0) from sign_data where name = '${sign[i]}';`
                sqlQuery(sql, (res) => {
                    res = JSON.parse(JSON.stringify(res))
                    res = Object.values(res[0])[0];//获得判断结果 1代表存在 0代表不存在
                    isRes.push(res)
                    if (i == sign.length - 1) {
                        resolve(isRes)
                    }
                })
            }
        })
    }

    //第二个方法，根据判断结果作出相应操作
    async function operate(isRes) {
        let signId = []
        return new Promise(function (resolve, reject) {
            if (isRes.length == 0) {
                resolve(signId)
            }
            for (let i in isRes) {
                //表中已存在标签
                if (isRes[i] == 1) {
                    let sql = `select id from sign_data where name = '${sign[i]}'`
                    sqlQuery(sql, (res2) => {
                        res2[0] = JSON.parse(JSON.stringify(res2[0]))
                        signId.push(res2[0].id)
                        if (i == isRes.length - 1) {
                            resolve(signId)
                        }
                    })
                }
                //表中尚未存在标签
                else {
                    let sql = `insert into sign_data(name,color) values("${sign[i]}","${color[i]}");`
                    sqlQuery(sql, (res2) => {
                        signId.push(res2.insertId)
                        if (i == isRes.length - 1) {
                            resolve(signId)
                        }
                    })
                }
            }
        })
    }

    //第三个方法，添加博客
    async function addBlog(signId) {
        //将数组sign和signId均转换成字符串的形式传入数据库
        sign = sign.join(",");
        signId = signId.join(",");
        let sql = sign.length == 0 ?
            `insert into blog_data(title,time,content,sign,signId,visit) values("${title}","${time}",'${content}',"","",0); `
            :
            `insert into blog_data(title,time,content,sign,signId,visit) values("${title}","${time}",'${content}',"${sign}","${signId}",0); `
        return new Promise(function (resolve, reject) {
            sqlQuery(sql, (data) => {
                //console.log(signId);
                resolve(data)
            })
        })
    }

    isChart().then(isRes => {
        operate(isRes).then(signId => {
            addBlog(signId)
        })
    })


}

//博文标题关键词搜索
// msg:关键词  data:所有博文信息
function searchBlog(msg, data) {
    //提取所有博文标题和id 组成数组
    let titleList = []
    for (let i in data) {
        titleList.push({
            id: data[i].id,
            title: data[i].title,
        })
    }
    return new Promise((resolve, reject) => {
        //将关键词和标题数组的各个元素进行比对，若含有关键词，则将其存储到结果中一并返回
        let result = []
        for (let i in titleList) {
            if (titleList[i].title.indexOf(msg) != -1) {
                result.push(titleList[i])
            }
            if (i == titleList.length - 1) {
                resolve(result)
            }
        }

    })

}

//将字符串转换为数组
function blogToArr(arr) {
    return arr.split(",") || []
}

//初始化博文列表顺序
function initArr(arr, index) {
    /* let curIndex = 0;
    for (let i in arr) {
        if (arr[i].signId.indexOf(1) != -1) {
            let index = arr[curIndex];
            arr[curIndex] = arr[i];
            arr[i] = index;
            curIndex++
        }
    }
    return arr */
    let obj = {}
    let curIndex = index
    for (let i = index; i < arr.length; i++) {
        if (i == arr.length - 1) {
            if (arr[i].signId.indexOf(1) == -1) {
                return arr
            }
            else {
                obj = arr[i]
                curIndex = arr.length
                arr.splice(i, 1);
                break;
            }
        }
        if (arr[i].signId.indexOf(1) != -1) {
            obj = arr[i]
            curIndex = i + 1
            arr.splice(i, 1);
            break;
        }
    }
    arr.unshift(obj);
    if (curIndex == arr.length) {
        return arr
    }
    else {
        return initArr(arr, curIndex)
    }
}



